#include "misc.hpp"
#include "debug.hpp"
#include "log.hpp"

using namespace wheels;
using namespace dm;

log :: log( const std::string& path , int page , int count )
{
    pt_egnx__ = std::make_shared< tinySeqFile >( path , count , page );
}

log :: ~log()
{
    pt_egnx__->sync();
}

bool log :: push( const std::string& data )
{
    return pt_egnx__->push( data );
}

bool log :: toText( const std::string& dst )
{
    if( dst.empty() ){
        ERROR_MSG( "导出路径为空" );
        debug::printCallstack();
        return false;
    }

    std::ofstream ofs( dst , std::ios_base::binary | std::ios_base::trunc );
    if( ofs.is_open() == false ){
        MSG_1( "打开文件失败：%s" , TRED , dst.c_str());
        debug::printCallstack();
        return false;
    }

    MSG_1( "导出到文件：%s" , TNORMAL , dst.c_str());
    std::string str;
    uint64_t idx = pt_egnx__->firstIndex() , count = 0;
    while( count < pt_egnx__->count() ){
        if( pt_egnx__->at( idx , str ) ){
            ofs << str << "\n";
            if( ofs.good() == false ){
                MSG_1( "写入文件失败：%s" , TRED , dst.c_str());
                debug::printCallstack();
                return false;
            }
            
        }
        idx ++;
        count ++;
        if( count % 100 ){
            std::cout << ".";
            std::cout.flush();
        }
    }

    std::cout << std::endl;
    ofs.close();
    return true;
}